# coding: utf-8
from django.db import transaction
from django.http import HttpResponseRedirect, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from common.overwrites import z_render_to_response
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required
from django.contrib.auth import logout as user_logout

from common.models.post import Post, PostTag, PostWithTag
from common.models.user import User, UserProfile
from common.models.notice import SystemNotice
from common.models.position import JPositionCounty, JPositionTown, JPositionVillage 
from django.conf import settings

from common.overwrites import z_render_to_response


@csrf_exempt
def index(request):
    system_notice = SystemNotice.objects.order_by('-id').first()
    tags = PostTag.objects.filter()
    for t in tags:
        post_ids = PostWithTag.objects.filter(tag=t).values_list('post', flat=True)
        t.posts = Post.objects.filter(id__in=post_ids, type='GK')

    return z_render_to_response('index.html', {
                                             'system_notice': system_notice,
                                             'tags': tags,
                                             # 'activity_users_count': request.activity_users_count
                                             })


def about(request):
    return z_render_to_response('about.html')


def declaration(request):
    return z_render_to_response('declaration.html')


@csrf_exempt
def sign_up(request):
    if request.method == 'GET':
        county_list = JPositionCounty.objects.filter(city_id=settings.XINYU_CITY_ID)
        return z_render_to_response('sign_up.html', {'county_list': county_list})
    if request.method == 'POST':
        # print '--------', request.POST
        # print '++++++=', request.FILES
        username = request.POST.get('username')
        email = request.POST.get('email')
        raw_password = request.POST.get('raw_password')

        county_id = request.POST.get('county_id')
        town_id = request.POST.get('town_id')
        village_id = request.POST.get('village_id')

        user = User.objects.create_user(username, email=email, raw_password=raw_password)
        if user:
            user = authenticate(username=username, password=raw_password)
            login(request, user)

            user_profile = UserProfile.objects.create(user=user,
                                                      true_name=request.POST.get('true_name'),
                                                      sex=request.POST.get('sex'),
                                                      declaration =  request.POST.get('declaration'),
                                                      avatar = request.FILES.get('avatar'))

            if county_id:
                user_profile.county = JPositionCounty.objects.get(county_id=int(county_id))
            if town_id:
                user_profile.town = JPositionTown.objects.get(town_id=int(town_id))
            if village_id:
                user_profile.village = JPositionVillage.objects.get(village_id=int(village_id))

            user_profile.save()
            return HttpResponseRedirect('/user/info')


@csrf_exempt
def sign_in(request):
    if request.method == 'GET':
        next = request.GET.get('next', '/')
        return z_render_to_response('sign_in.html', {'next': next})

    if request.method == 'POST':
        username = request.POST.get('username')
        raw_password = request.POST.get('raw_password')
        user = authenticate(username=username, password=raw_password)

        if user is not None:
            login(request, user)
            return JsonResponse({'success': True})
        else:
            return JsonResponse({'success': False})


def logout(request):
    user_logout(request)
    return HttpResponseRedirect('/')



